package com.useeinfo.oa.open.admin;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.entity.AuditFlow;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.maintaining.biz.PeriodInstallBiz;
import com.useeinfo.oa.modules.maintaining.entity.PeriodInstall;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 周期设置表
 */
@Controller
@RequestMapping("/web/admin/manage/periodInstall")
public class PeriodInstallAdminManagerAction {
    private final static Logger logger = LoggerFactory.getLogger(PeriodInstallAdminManagerAction.class);

    @Autowired
    private PeriodInstallBiz periodInstallBiz;
    @Autowired
    private HttpServletRequest request;


    /**
     * 周期列表跳转页
     */
    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/periodInstall/list");
        return modelAndView;
    }

    /**
     * 周期列表
     *
     * @param pageSize
     * @param pageNo
     * @return
     */
    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(String pageNo, String pageSize, String periodName) {
        QueryParam queryParam = new QueryParam(pageNo, pageSize);
        if (!StringUtils.isEmpty(periodName)) {
            queryParam.getSqlMap().put("periodName", periodName);
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        return periodInstallBiz.findJSONList(queryParam);

    }

    /**
     * 新增周期设置
     */
    @RequestMapping("/addOrEdit")
    @ResponseBody
    public ResultDto addOrEdit(PeriodInstall periodInstall, @RequestParam(value = "dateArray[]", required = false) String[] dateArray,
                               @RequestParam(value = "timeArray[]", required = false) String[] timeArray,
                               @RequestParam(value = "weekArray", required = false) String[] weekArray) {
        try {
            Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
            if (null == enterprise) {
                return ResultUtil.error("当前用户企业信息有误");
            }
            if (null == timeArray && !periodInstall.getType().equals("时")) {
                return ResultUtil.error("时间不可为空，请选择时间");
            }
            periodInstall.setEnterprise(enterprise);
            if ("2".equals(periodInstall.getPlanType())) {
                periodInstall.setAllDate(JSONArray.toJSONString(dateArray));
                periodInstall.setFrequency(null);
                periodInstall.setType(null);
            } else {
                periodInstall.setAllDate(JSONArray.toJSONString(new JSONArray()));
            }
            if ("3".equals(periodInstall.getPlanType())) {
                periodInstall.setWeek(JSONArray.toJSONString(weekArray));
                periodInstall.setFrequency(null);
                periodInstall.setType(null);
            } else {
                periodInstall.setWeek(JSONArray.toJSONString(new JSONArray()));
            }
            //对时间进行排序
            if(timeArray!=null&&timeArray.length>0){
                Arrays.sort(timeArray);
            }
            periodInstall.setTime(JSONArray.toJSONString(timeArray));

            periodInstallBiz.addOrUpdate(periodInstall);
            return ResultUtil.success();
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
    }


    /**
     * 周期编辑接口
     *
     * @param id id
     * @return 周期详情
     */
    @RequestMapping("/editPage")
    public ModelAndView editPage(String id) {
        ModelAndView modelAndView = new ModelAndView();
        PeriodInstall periodInstall = periodInstallBiz.findModel(StringConverters.ToLong(id));
        if (null == periodInstall) {
            periodInstall = new PeriodInstall();
            periodInstall.setAllDate(JSONArray.toJSONString(new JSONArray()));
            periodInstall.setTime(JSONArray.toJSONString(new JSONArray()));
        }
        modelAndView.addObject("periodInstall", periodInstall);
        modelAndView.setViewName("pages/admin/periodInstall/edit");
        return modelAndView;
    }

    /**
     * 删除周期设置
     *
     * @param installIds
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String installIds) {
        try {
            JSONArray assignArray = JSONObject.parseArray(installIds);
            try {
                for (int i = 0; i < assignArray.size(); i++) {
                    String installId = assignArray.get(i).toString();
                    logger.info("installId为：" + installId);
                    PeriodInstall periodInstall = periodInstallBiz.findModel(StringConverters.ToLong(installId));
                    if (null != periodInstall) {
                        periodInstallBiz.delete(StringConverters.ToLong(installId));
                    }
                }
            } catch (Exception e) {
                return ResultUtil.error("此数据有关联数据");
            }

            return ResultUtil.success();
        } catch (Exception e) {
            return ResultUtil.error();
        }

    }

    /**
     * 获取周期选择数据
     *
     * @param q
     * @return
     */
    @RequestMapping("/getPeriodInstallSelect")
    @ResponseBody
    public List<SelectVO> getPeriodInstallSelect(@RequestParam(value = "q", required = false) String q, HttpServletRequest request,
                                                 @RequestParam(value = "id", required = false) String id) {
        List<SelectVO> selectVOS = new ArrayList<>();
        PeriodInstall periodInstall = periodInstallBiz.findModel(StringConverters.ToLong(id));
        if (periodInstall != null) {
            selectVOS.add(new SelectVO(periodInstall.getName(), periodInstall.getId() + ""));
        }
        QueryParam queryParam = new QueryParam("-1", "-1");
        queryParam.getSqlMap().put("searchCode", q);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        List<PeriodInstall> periodInstalls = periodInstallBiz.findList(queryParam);
        periodInstalls.forEach(module -> selectVOS.add(new SelectVO(module.getName(), module.getId() + "")));
        return selectVOS;
    }

}
